﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public class TrainingCoursesTypesCollection : AbstractCollection
    {
        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        protected static List<TrainingCoursesTypes> _list;

        /// <summary>
        /// Список объектов
        /// </summary>
        public List<TrainingCoursesTypes> TrainingCoursesTypesList
        {
            get
            {
                return Entities.TrainingCoursesTypes.AsNoTracking().ToList();
                if (_list == null)
                    _list = DB.Entities.TrainingCoursesTypes.ToList();
                return _list;
            }
        }

        /// <summary>
        /// список активных объектов
        /// </summary>
        public List<TrainingCoursesTypes> TrainingCoursesTypesActiveList
        {
            get
            {
                var result = new List<TrainingCoursesTypes>();
                if (TrainingCoursesTypesList.Count < 1) return result;
                result.AddRange(TrainingCoursesTypesList.Where(item => item.IsActive));
                return result;
            }
        }

        /// <summary>
        /// Возвращает список, где на первом месте "Выбрать всех"
        /// </summary>
        public List<TrainingCoursesTypes> DropDownList
        {
            get
            {
                var result = new List<TrainingCoursesTypes>();
                var selectAllItem = new TrainingCoursesTypes {NameRu = "Выбрать всех", NameEn = "Select All"};
                result.Add(selectAllItem);
                result.AddRange(TrainingCoursesTypesActiveList.OrderBy(p => p.NameRu));
                return result;
            }
        }

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            _list = null;
        }

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            return _list;
        }

        /// <summary>
        /// Получение элемента из коллекции по идентификатору
        /// </summary>
        /// <param name="itemId">Идентификатор</param>
        /// <returns>Элемент</returns>
        public override object GetItemById(int itemId)
        {
            return Entities.TrainingCoursesTypes.Find(itemId);
        }

        /// <summary>
        /// Получить списсок типой курсов из строки зарделенной сепараторами
        /// </summary>
        /// <param name="coursesTypesStr"></param>
        /// <param name="separatorStr"></param>
        /// <returns></returns>
        public List<TrainingCoursesTypes> GetCoursesTypesFromString(string coursesTypesStr, char separatorStr = ';')
        {
            var result = new List<TrainingCoursesTypes>();
            string[] trainersArray = coursesTypesStr.Split(separatorStr);
            foreach (string item in trainersArray)
            {
                int id = GetIdByName(item.Trim());
                if (id <= 0) continue;
                var trainerItem = (TrainingCoursesTypes) GetItemById(id);
                if (trainerItem != null)
                {
                    result.Add(trainerItem);
                }
            }
            return result;
        }

        /// <summary>
        /// Получить список типов курса по идентификатору курса
        /// </summary>
        /// <param name="idCourse"></param>
        /// <returns></returns>
        public List<TrainingCoursesTypes> GetTrainingsCoursesTypesByCourseId(int idCourse)
        {
            var result = new List<TrainingCoursesTypes>();
            var bindingCol = new TrainingsCoursesAndTypesCollection();
            var coursesTypesCol = new TrainingCoursesTypesCollection();
            foreach (TrainingsCoursesAndTypes item in bindingCol.TrainingsCoursesAndTypesList)
            {
                if (item.IdTrainingsCourse == idCourse)
                {
                    var courseType = (TrainingCoursesTypes) coursesTypesCol.GetItemById(item.IdTraningCoursesType);
                    if (courseType != null)
                    {
                        result.Add(courseType);
                    }
                }
            }
            return result;
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin)
        {
            var newObject = (TrainingCoursesTypes) item;
            if (newObject == null)
                return false;

            var object4Update = GetItemByIdFromDatabase(newObject.GetKeyValue()) as TrainingCoursesTypes;
            if (object4Update == null)
                return false;

            if (!string.IsNullOrEmpty(newObject.NameRu))
                object4Update.NameRu = newObject.NameRu;

            if (!string.IsNullOrEmpty(newObject.NameEn))
                object4Update.NameEn = newObject.NameEn;

            if (!string.IsNullOrEmpty(newObject.DescriptionRu))
                object4Update.DescriptionRu = newObject.DescriptionRu;

            if (!string.IsNullOrEmpty(newObject.DescriptionEn))
                object4Update.DescriptionEn = newObject.DescriptionEn;

            object4Update.IsActive = newObject.IsActive;
            return base.Update(object4Update, userLogin);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(TrainingCoursesTypesList);
        }

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (TrainingCoursesTypes);
        }

        #endregion
    }
}